<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="所属项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable filterable @change="handleQuery"
          style="width: 200px">
          <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="meetingDate">
        <el-date-picker v-model="queryParams.meetingDate" type="date" placeholder="请选择停工日期" clearable
          value-format="yyyy-MM-dd" @change="handleQuery" style="width: 190px" />
      </el-form-item>
      <!-- <el-form-item>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item> -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['production:bizStoppageLog:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['production:bizStoppageLog:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['production:bizStoppageLog:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bizStoppageLogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" width="100" /> -->
      <!-- <el-table-column label="所属项目ID" align="center" prop="projectId" width="120" /> -->

      <el-table-column label="名称" align="center" prop="meetingDate" width="180">
        <template slot-scope="scope">
          {{ getDateOnly(scope.row.meetingDate) + '日停工日志' }}
        </template>
      </el-table-column>
      <el-table-column label="填报时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          {{ changeTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="填报人" align="center" prop="createBy" />
      <el-table-column label="所属项目" align="center" prop="projectId" width="170">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="getProjectNameById(scope.row.projectId)" placement="top">
            <span
              style="max-width: 120px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle;"
              :title="getProjectNameById(scope.row.projectId)">
              {{ getProjectNameById(scope.row.projectId) }}
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <!-- <el-table-column label="天气" align="center" prop="weather" />
      <el-table-column label="管理人员数量" align="center" prop="managerCount" />
      <el-table-column label="班组成员数量" align="center" prop="teamMemberCount" />
      <el-table-column label="桩基设备型号" align="center" prop="baseDeviceModel" />
      <el-table-column label="桩基设备数量" align="center" prop="baseDeviceCount" />
      <el-table-column label="停工时间-开始" align="center" prop="stoppageTimeStart" width="200">
        <template slot-scope="scope">
          {{ changeTime(scope.row.stoppageTimeStart) }}
        </template>
      </el-table-column>
      <el-table-column label="停工时间-结束" align="center" prop="stoppageTimeEnd" width="200">
        <template slot-scope="scope">
          {{ changeTime(scope.row.stoppageTimeEnd) }}
        </template>
      </el-table-column> -->
      <el-table-column label="巡查频次" align="center" prop="patrolFrequency" />
      <!-- <el-table-column label="巡查时段" align="center" prop="patrolPeriod" /> -->
      <el-table-column label="异常情况" width="120" align="center" prop="isAbnormal">
        <template slot-scope="scope">
          <el-tag v-if="Number(scope.row.isAbnormal) === 1" type="success">正常</el-tag>
          <el-tag v-else type="danger">异常</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="异常情况说明" align="center" prop="abnormalDescription" show-overflow-tooltip /> -->
      <el-table-column label="监控设备状态" width="120" align="center" prop="monitorStatus">
        <template slot-scope="scope">
          <el-tag v-if="Number(scope.row.monitorStatus) === 1" type="success">正常</el-tag>
          <el-tag v-else type="danger">故障</el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="故障说明" align="center" prop="faultDescription" show-overflow-tooltip /> -->
      <!-- <el-table-column label="上传照片URL" align="center" prop="imageList" show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.imageList">{{ getPhotoCount(scope.row.imageList) }} 张</span>
          <span v-else>--</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="其他补充说明" align="center" prop="remark" show-overflow-tooltip /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['production:bizStoppageLog:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['production:bizStoppageLog:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="820px" append-to-body>
      <el-form ref="form" :model="form" :inline="true" :rules="rules" label-width="140px">
        <el-form-item label="选择项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" filterable style="width:190px"
            @change="onProjectChange">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="所属项目" prop="projectName">
          <el-input v-model="form.projectName" placeholder="所属项目" style="width:190px" readonly />
        </el-form-item> -->
        <el-form-item label="日期" prop="meetingDate">
          <el-date-picker v-model="form.meetingDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择日期"
            style="width:190px" />
        </el-form-item>
        <el-form-item label="天气" prop="weather">
          <el-input v-model="form.weather" placeholder="请输入天气" />
        </el-form-item>
        <el-form-item label="管理人员数量" prop="managerCount">
          <el-input v-model="form.managerCount" placeholder="请输入管理人员数量" @input="validatePositiveInteger('managerCount')"
            @blur="formatPositiveInteger('managerCount')" />
        </el-form-item>
        <el-form-item label="班组成员数量" prop="teamMemberCount">
          <el-input v-model="form.teamMemberCount" placeholder="请输入班组成员数量"
            @input="validatePositiveInteger('teamMemberCount')" @blur="formatPositiveInteger('teamMemberCount')" />
        </el-form-item>
        <el-form-item label="桩基设备型号" prop="baseDeviceModel">
          <el-input v-model="form.baseDeviceModel" placeholder="请输入桩基设备型号" />
        </el-form-item>
        <el-form-item label="桩基设备数量" prop="baseDeviceCount">
          <el-input v-model="form.baseDeviceCount" placeholder="请输入桩基设备数量"
            @input="validatePositiveInteger('baseDeviceCount')" @blur="formatPositiveInteger('baseDeviceCount')" />
        </el-form-item>
        <!-- <el-form-item label="停工时间-开始" prop="stoppageTimeStart">
          <el-date-picker v-model="form.stoppageTimeStart" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择停工开始时间" style="width:190px" />
        </el-form-item>
        <el-form-item label="停工时间-结束" prop="stoppageTimeEnd">
          <el-date-picker v-model="form.stoppageTimeEnd" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择停工结束时间" style="width:190px" />
        </el-form-item> -->
        <el-form-item style="width: 100%;"></el-form-item>
        <div
          style="font-size: 16px; font-weight: bold; color: #303133; padding: 15px 0 10px 0; margin-top: 10px; width: 100%;border-bottom: null;">
          当日巡查情况</div>
        <el-form-item label="巡查频次(/次)" prop="patrolFrequency">
          <el-input v-model="form.patrolFrequency" placeholder="请输入巡查频次"
            @input="validatePositiveInteger('patrolFrequency')" @blur="formatPositiveInteger('patrolFrequency')" />
        </el-form-item>
        <el-form-item label="巡查时段" prop="patrolPeriod">
          <el-input v-model="form.patrolPeriod" placeholder="请输入巡查时段" />
        </el-form-item>
        <el-form-item label="异常情况" prop="isAbnormal">
          <el-radio-group v-model="form.isAbnormal" @change="handleAbnormalChange">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isAbnormal !== 1" label="异常情况说明" prop="abnormalDescription" :required="true"
          style="margin-left: 28px;">
          <el-input v-model="form.abnormalDescription" style="width:190px;border-bottom: none;" type="textarea"
            placeholder="请输入异常情况说明" />
        </el-form-item>
        <div class="form-section-divider"></div>
        <el-form-item label="监控设备状态" prop="monitorStatus">
          <el-radio-group v-model="form.monitorStatus" @change="handleMonitorStatusChange">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">故障</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.monitorStatus !== 1" label="故障说明" prop="faultDescription" :required="true">
          <el-input v-model="form.faultDescription" style="width:190px" type="textarea" placeholder="请输入监控设备状态说明" />
        </el-form-item>
        <!-- <el-form-item label="故障说明" prop="faultDescription">
          <el-input v-model="form.faultDescription" type="textarea" style="width:190px" placeholder="请输入故障说明" />
        </el-form-item> -->
        <el-form-item label="巡查照片" class="upload-form-item" prop="imageList">
          <div class="upload-container">
            <el-upload ref="upload" drag action="#" :auto-upload="true" list-type="picture-card"
              :on-change="onUploadChange" :on-remove="onUploadRemove" :on-exceed="onUploadExceed"
              :file-list="uploadFileList" accept="image/*" class="upload-component" :http-request="handleCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅用于随单据上传的图片凭证，支持多张
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="其他补充说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" style="width:560px" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="detailOpen" width="900px" append-to-body class="daily-detail-dialog">
      <div class="daily-detail-title">停工日志详情</div>

      <div class="daily-section-title">基本信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">所属项目</th>
              <td class="value">{{ getProjectNameById(detailForm.projectId) || detailForm.projectName }}</td>
            </tr>
            <tr>
              <th class="left-align">停工日期</th>
              <td class="value">{{ getDateOnly(detailForm.meetingDate) }}</td>
            </tr>
            <tr>
              <th class="left-align">天气</th>
              <td class="value">{{ detailForm.weather }}</td>
            </tr>
            <tr>
              <th class="left-align">管理人员数量</th>
              <td class="value">{{ detailForm.managerCount }}</td>
            </tr>

            <tr>
              <th class="left-align">巡查频次</th>
              <td class="value">{{ detailForm.patrolFrequency }}</td>
            </tr>
          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">桩基设备型号</th>
              <td class="value">{{ detailForm.baseDeviceModel }}</td>
            </tr>
            <tr>
              <th class="left-align">桩基设备数量</th>
              <td class="value">{{ detailForm.baseDeviceCount }}</td>
            </tr>
            <!-- <tr>
              <th class="left-align">停工开始</th>
              <td class="value">{{ changeTime(detailForm.stoppageTimeStart) }}</td>
            </tr>
            <tr>
              <th class="left-align">停工结束</th>
              <td class="value">{{ changeTime(detailForm.stoppageTimeEnd) }}</td>
            </tr> -->
            <tr>
              <th class="left-align">巡查时段</th>
              <td class="value">{{ detailForm.patrolPeriod }}</td>
            </tr>
            <tr>
              <th class="left-align">班组成员数量</th>
              <td class="value">{{ detailForm.teamMemberCount }}</td>
            </tr>
          </table>
        </div>
      </div>

      <div class="daily-section-title">异常与巡查</div>
      <table class="daily-detail-table">
        <tr>
          <th class="center-bg">
            <span class="icon">⚠️</span>异常情况
          </th>
          <td class="value">
            {{ detailForm.isAbnormal === 1 ? '正常' : '异常' }}
          </td>
        </tr>
        <tr v-if="detailForm.isAbnormal !== 1">
          <th class="center-bg">
            <span class="icon">🔒</span>异常情况说明
          </th>
          <td class="value">
            <div class="text-block">{{ detailForm.abnormalDescription }}</div>
          </td>
        </tr>
        <tr>
          <th class="center-bg">
            <span class="icon">📹</span>监控设备状态
          </th>
          <td class="value">
            {{ detailForm.monitorStatus === 1 ? '正常' : '故障' }}
          </td>
        </tr>
        <tr v-if="detailForm.monitorStatus !== 1">
          <th class="center-bg">
            <span class="icon">📝</span>故障说明
          </th>
          <td class="value">
            <div class="text-block">{{ detailForm.faultDescription }}</div>
          </td>
        </tr>
        <!-- <tr>
          <th class="center-bg">故障说明</th>
          <td class="value">
            <div class="text-block">{{ detailForm.faultDescription }}</div>
          </td>
        </tr> -->
        <tr>
          <th class="center-bg">其他补充说明</th>
          <td class="value">
            <div class="text-block">{{ detailForm.remark }}</div>
          </td>
        </tr>
      </table>

      <div class="daily-section-title" v-if="detailImageUrls.length || detailFileList.length">巡查照片</div>
      <div v-if="detailImageUrls && detailImageUrls.length > 0" class="image-display-container">
        <div v-for="(url, index) in detailImageUrls" :key="`display-${index}`" class="image-item">
          <el-image :src="url" :preview-src-list="detailImageUrls" fit="cover" class="detail-image">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
      </div>

      <div v-if="detailFileList && detailFileList.length > 0" class="daily-section-title">附件信息</div>
      <div v-if="detailFileList && detailFileList.length > 0" class="file-display-container">
        <div v-for="(file, index) in detailFileList" :key="`file-${index}`" class="file-item">
          <div class="file-info">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ file.fileName }}</span>
            <div class="file-actions">
              <el-button type="primary" size="mini" icon="el-icon-download" @click="handleFileDownload(file)">
                下载
              </el-button>
              <el-button type="success" size="mini" icon="el-icon-view" @click="handleFilePreview(file)">
                预览
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="previewDialogVisible" width="60vw" top="5vh" :title="getPreviewTitle()"
      @close="previewFile = null">
      <div v-if="previewFile">
        <el-image v-if="getFileType(previewFile.fileName) === 'image'" :src="previewFile.downloadUrl"
          :preview-src-list="[previewFile.downloadUrl]" fit="contain"
          style="max-width:100%;max-height:70vh;display:block;margin:auto;cursor:pointer;">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <iframe v-else-if="['pdf', 'word', 'excel', 'ppt'].includes(getFileType(previewFile.fileName))"
          :src="previewFile.downloadUrl" style="width:100%;height:70vh;border:none;"></iframe>
        <div v-else style="text-align:center;padding:40px 0;color:#888;">
          暂不支持该类型文件的在线预览，请下载后查看。
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBizStoppageLog, getBizStoppageLog, delBizStoppageLog, addBizStoppageLog, updateBizStoppageLog } from "@/api/production/bizStoppageLog";
import { listAllProjectContractInfo } from "@/api/production/projectContractInfo";
import { addImg } from "@/api/cost/materialLedger";
import { fileLinkTransfer, fileLinkLooking } from "@/api/production/projectFileInfo";

export default {
  name: "BizStoppageLog",
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      bizStoppageLogList: [],
      title: "",
      open: false,
      projectOptions: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        projectName: null,
        meetingDate: null,
        weather: null,
        managerCount: null,
        teamMemberCount: null,
        baseDeviceModel: null,
        baseDeviceCount: null,
        stoppageTimeStart: null,
        stoppageTimeEnd: null,
        patrolFrequency: null,
        patrolPeriod: null,
        isAbnormal: null,
        abnormalDescription: null,
        monitorStatus: null,
        faultDescription: null,
        imageList: null,
        remark: null,
      },
      form: {},
      rules: {
        projectId: [{ required: true, message: "所属项目不能为空", trigger: "change" }],
        projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
        meetingDate: [{ required: true, message: "日期不能为空", trigger: "change" }],
        weather: [{ required: true, message: "天气不能为空", trigger: "blur" }],
        managerCount: [{ required: true, message: "管理人员数量不能为空", trigger: "blur" }],
        teamMemberCount: [{ required: true, message: "班组成员数量不能为空", trigger: "blur" }],
        baseDeviceModel: [{ required: true, message: "桩基设备型号不能为空", trigger: "blur" }],
        baseDeviceCount: [{ required: true, message: "桩基设备数量不能为空", trigger: "blur" }],
        stoppageTimeStart: [{ required: true, message: "停工开始时间不能为空", trigger: "change" }],
        stoppageTimeEnd: [{ required: true, message: "停工结束时间不能为空", trigger: "change" }],
        patrolFrequency: [{ required: true, message: "巡查频次不能为空", trigger: "blur" }],
        patrolPeriod: [{ required: true, message: "巡查时段不能为空", trigger: "blur" }],
        isAbnormal: [{ required: true, message: "异常情况不能为空", trigger: "change" }],
        abnormalDescription: [
          { required: true, message: "异常情况说明不能为空", trigger: "blur" }
        ],
        monitorStatus: [{ required: true, message: "监控设备状态不能为空", trigger: "change" }],
        monitorStatusRemark: [
          { required: true, message: "监控设备状态说明不能为空", trigger: "blur" }
        ],
        faultDescription: [{ required: true, message: "故障说明不能为空", trigger: "blur" }],
        imageList: [{ type: "array", required: true, message: "请上传巡查照片", trigger: "change" }],
      },
      detailOpen: false,
      detailForm: {},
      detailImageUrls: [],
      detailFileList: [],
      uploadFileList: [],
      previewDialogVisible: false,
      previewImageUrl: "",
      previewFile: null,
    };
  },
  created() {
    this.fetchProjectOptions();
    this.getList();
  },
  methods: {
    fetchProjectOptions() {
      listAllProjectContractInfo().then(res => {
        this.projectOptions = res.data || [];
        if (this.projectOptions.length === 1 && !this.queryParams.projectId) {
          this.queryParams.projectId = this.projectOptions[0].id;
          this.handleQuery();
        }
      });
    },
    getList() {
      this.loading = true;
      listBizStoppageLog(this.queryParams).then(response => {
        const rows = Array.isArray(response.rows)
          ? response.rows.map(item => this.normalizeStatusFields(item))
          : [];
        this.bizStoppageLogList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        projectId: null,
        projectName: null,
        meetingDate: null,
        weather: null,
        managerCount: null,
        teamMemberCount: null,
        baseDeviceModel: null,
        baseDeviceCount: null,
        stoppageTimeStart: null,
        stoppageTimeEnd: null,
        patrolFrequency: null,
        patrolPeriod: null,
        isAbnormal: 1,
        abnormalDescription: null,
        monitorStatus: 1,
        monitorStatusRemark: null,
        faultDescription: null,
        imageList: [],
        remark: null,
      };
      this.uploadFileList = [];
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.projectId = null;
      this.queryParams.meetingDate = null;
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加停工日志";
    },
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      const response = await getBizStoppageLog(id);
      const formData = this.normalizeStatusFields(response.data || {});
      formData.imageList = this.normalizeImageListData(formData.imageList);
      this.form = formData;
      await this.processImageListForDisplay();
      this.open = true;
      this.title = "修改停工日志";
    },
    async handleDetail(row) {
      const response = await getBizStoppageLog(row.id);
      const detailData = this.normalizeStatusFields(response.data || {});
      detailData.imageList = this.normalizeImageListData(detailData.imageList);
      this.detailForm = detailData;
      await this.processDetailImageAndFiles();
      this.detailOpen = true;
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) return;
        const payload = {
          ...this.form
        };
        const request = payload.id != null ? updateBizStoppageLog(payload) : addBizStoppageLog(payload);
        request.then(() => {
          this.$modal.msgSuccess(payload.id != null ? "修改成功" : "新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(() => {
        return delBizStoppageLog(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    handleExport() {
      this.download('production/bizStoppageLog/export', {
        ...this.queryParams
      }, `bizStoppageLog_${new Date().getTime()}.xlsx`);
    },
    onProjectChange(id) {
      const item = this.projectOptions.find(p => p.id === id);
      this.form.projectName = item ? item.projectName : null;
    },
    changeTime(time) {
      if (!time) return '';
      const date = new Date(time);
      if (isNaN(date.getTime())) return time;
      const pad = n => (n < 10 ? '0' + n : n);
      const y = date.getFullYear();
      const m = pad(date.getMonth() + 1);
      const d = pad(date.getDate());
      const h = pad(date.getHours());
      const min = pad(date.getMinutes());
      const s = pad(date.getSeconds());
      return `${y}-${m}-${d} ${h}:${min}:${s}`;
    },
    getDateOnly(datetime) {
      if (!datetime) return '';
      const str = typeof datetime === 'string' ? datetime : this.changeTime(datetime);
      const match = str.match(/^\d{4}-\d{2}-\d{2}/);
      return match ? match[0] : str;
    },
    getProjectNameById(projectId) {
      const item = this.projectOptions.find(p => p.id === projectId);
      return item ? item.projectName : null;
    },
    validatePositiveInteger(fieldName) {
      if (!this.form[fieldName]) return;
      this.form[fieldName] = this.form[fieldName].replace(/\D/g, '');
    },
    formatPositiveInteger(fieldName) {
      if (!this.form[fieldName]) return;
      const num = parseInt(this.form[fieldName], 10);
      this.form[fieldName] = isNaN(num) ? '' : num.toString();
    },
    async handleCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }
      try {
        const { msg: filePath } = await addImg(file);
        if (!filePath) throw new Error("未获取到文件路径");
        const { data: { url } } = await fileLinkTransfer(filePath);
        if (!url) throw new Error("未获取到可访问的图片链接");
        const fileItem = {
          name: file.name || "image.jpg",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath,
        };
        this.uploadFileList = [...this.uploadFileList, fileItem];
        if (!Array.isArray(this.form.imageList)) this.form.imageList = [];
        this.form.imageList.push(filePath);
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("图片上传失败");
        param?.onError?.(err);
      }
    },
    onUploadChange(file, fileList) {
      this.uploadFileList = fileList;
    },
    onUploadRemove(file, fileList) {
      const { url } = file || {};
      if (url) {
        const fileItem = this.uploadFileList.find(item => item.url === url);
        if (fileItem?.originalPath && Array.isArray(this.form.imageList)) {
          const index = this.form.imageList.indexOf(fileItem.originalPath);
          if (index > -1) {
            this.form.imageList.splice(index, 1);
          }
        }
      }
      this.uploadFileList = fileList;
    },
    onUploadExceed(files, fileList) {
      this.$message.warning(`当前限制选择 ${fileList.length} 张图片，已选择 ${files.length} 张`);
    },
    handleUploadPreview(file) {
      this.previewImageUrl = file.url;
      this.previewDialogVisible = true;
    },
    async handleFileDownload(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的下载链接");
        return;
      }
      try {
        const res = await fileLinkTransfer(file.downloadUrl);
        const newUrl = res.data.url;
        if (!newUrl) {
          this.$message.error("获取下载链接失败");
          return;
        }
        const a = document.createElement("a");
        a.href = newUrl;
        a.download = file.fileName || "";
        a.target = "_blank";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        this.$message.error("下载失败");
      }
    },
    async handleFilePreview(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的预览链接");
        return;
      }
      try {
        let newUrl = '';
        const fileType = this.getFileType(file.fileName);
        if (fileType === 'image') {
          const res = await fileLinkTransfer(file.downloadUrl);
          newUrl = res.data.url;
        } else if (['pdf', 'word', 'excel', 'ppt'].includes(fileType)) {
          const res = await fileLinkLooking(file.downloadUrl);
          newUrl = res.data.url;
        } else {
          newUrl = file.downloadUrl;
        }
        if (!newUrl) {
          this.$message.error("获取预览链接失败");
          return;
        }
        this.previewFile = { ...file, downloadUrl: newUrl };
        this.previewDialogVisible = true;
      } catch (e) {
        this.$message.error("预览失败");
      }
    },
    getPreviewTitle() {
      if (this.previewFile?.fileName) {
        return this.previewFile.fileName;
      }
      return "文件预览";
    },
    handleAbnormalChange(value) {
      // 当选择改变时，触发异常情况说明字段的验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('abnormalDescription');
        }
      });
    },
    handleMonitorStatusChange(value) {
      // 当选择改变时，触发监控设备状态说明字段的验证
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('faultDescription');
        }
      });
    },
    async processImageListForDisplay() {
      if (!this.form.imageList?.length) {
        this.uploadFileList = [];
        return;
      }
      this.uploadFileList = [];
      for (let i = 0; i < this.form.imageList.length; i++) {
        const url = this.form.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          this.uploadFileList.push({
            name: fileName || `image_${i + 1}.jpg`,
            url: displayUrl,
            uid: `existing_image_${i}`,
            originalPath: url,
          });
        } catch (error) {
          console.error("processPhotoListForDisplay - 转换失败:", error);
          const fileName = this.getFileNameFromUrl(url);
          this.uploadFileList.push({
            name: fileName || `image_${i + 1}.jpg`,
            url,
            uid: `existing_image_${i}`,
            originalPath: url,
          });
        }
      }
    },
    async processDetailImageAndFiles() {
      if (!this.detailForm.imageList?.length) {
        this.detailImageUrls = [];
        this.detailFileList = [];
        return;
      }
      this.detailImageUrls = [];
      this.detailFileList = [];
      for (let i = 0; i < this.detailForm.imageList.length; i++) {
        const url = this.detailForm.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);
          if (this.isImageFile(fileType)) {
            this.detailImageUrls.push(displayUrl);
          } else {
            this.detailFileList.push({
              fileName,
              downloadUrl: url,
              displayUrl,
              fileType,
            });
          }
        } catch (error) {
          console.error("processDetailImageAndFiles - 转换失败:", error);
        }
      }
    },
    normalizeImageListData(imageList) {
      if (!imageList) return [];
      if (Array.isArray(imageList)) {
        return imageList.filter(item => !!item);
      }
      if (typeof imageList === 'string') {
        let parsed = [];
        try {
          const temp = JSON.parse(imageList);
          if (Array.isArray(temp)) {
            parsed = temp;
          }
        } catch (error) {
          parsed = imageList.split(',').map(item => item.trim()).filter(item => !!item);
        }
        return parsed;
      }
      return [];
    },
    normalizeStatusFields(record = {}) {
      if (!record || typeof record !== 'object') {
        return {
          isAbnormal: 1,
          monitorStatus: 1,
        };
      }
      return {
        ...record,
        isAbnormal: this.normalizeStatusValue(record.isAbnormal),
        monitorStatus: this.normalizeStatusValue(record.monitorStatus),
      };
    },
    normalizeStatusValue(value) {
      if (value === undefined || value === null || value === '') {
        return 1;
      }
      const parsed = Number(value);
      return Number.isNaN(parsed) ? 1 : parsed;
    },
    getFileNameFromUrl(url) {
      if (!url) return 'unknown';
      const parts = url.split('/');
      return parts[parts.length - 1] || 'unknown';
    },
    async getDisplayImageUrl(url) {
      if (!url) return "";
      try {
        const { data: { url: accessibleUrl } } = await fileLinkTransfer(url);
        return accessibleUrl || url;
      } catch (error) {
        console.error("getDisplayImageUrl - 转换失败:", error);
        return url;
      }
    },
    getFileType(fileName) {
      if (!fileName) return 'unknown';
      const extension = fileName.split('.').pop().toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
      const pdfTypes = ['pdf'];
      const wordTypes = ['doc', 'docx'];
      const excelTypes = ['xls', 'xlsx'];
      const pptTypes = ['ppt', 'pptx'];
      if (imageTypes.includes(extension)) return 'image';
      if (pdfTypes.includes(extension)) return 'pdf';
      if (wordTypes.includes(extension)) return 'word';
      if (excelTypes.includes(extension)) return 'excel';
      if (pptTypes.includes(extension)) return 'ppt';
      return 'unknown';
    },
    isImageFile(fileType) {
      return fileType === 'image';
    },
    getPhotoCount(imageList) {
      if (!imageList) return 0;
      if (Array.isArray(imageList)) return imageList.length;
      if (typeof imageList === 'string') {
        return imageList.split(',').filter(item => !!item).length;
      }
      return 0;
    }
  }
};
</script>

<style scoped>
.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 26px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 24px;
  text-align: center;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 140px;
  color: #6b7a90;
  font-weight: normal;
  text-align: right;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table th.left-align {
  text-align: center;
  background: #f7fafd;
}

.daily-detail-table th.center-bg {
  text-align: center;
  vertical-align: middle;
  background: #f7fafd;
}

.text-block {
  white-space: pre-wrap;
  border-radius: 4px;
  padding: 10px 12px;
  min-height: 48px;
  border: 1px solid #e3e6ed;
  background: #fff;
  color: #444;
  font-size: 15px;
  margin: 0;
}

.icon {
  display: inline-block;
  width: 18px;
  height: 18px;
  vertical-align: middle;
  margin-right: 6px;
  opacity: 0.7;
}

.image-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 16px 0;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.detail-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.file-display-container {
  margin: 16px 0;
}

.file-item {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.2s;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #409eff;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info i {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 14px;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.form-section-divider {
  width: 100%;
  display: block;
  height: 0;
  margin: 12px 0;
}

.upload-container {
  width: 100%;
  overflow: hidden;
  margin-bottom: 10px;
}

.upload-component {
  width: 100%;
}

.upload-form-item {
  margin-bottom: 20px;
}

.upload-form-item .el-form-item__content {
  margin-bottom: 10px;
}

::v-deep .el-form--inline .upload-form-item {
  width: 100%;
  display: flex;
  align-items: flex-start;
}

::v-deep .el-form--inline .upload-form-item .el-form-item__content {
  flex: 1;
  width: auto;
}

::v-deep .upload-component .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 118px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

::v-deep .upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
}

::v-deep .upload-component .el-upload-list--picture-card {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  margin: 0;
}

::v-deep .el-dialog__body .upload-container {
  max-width: 100%;
  box-sizing: border-box;
}

::v-deep .upload-component .el-upload-dragger {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

::v-deep .upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

.mb8 {
  margin-bottom: 10px;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }

  .upload-form-item .el-form-item__content {
    width: 100%;
  }
}

::v-deep .el-form--inline .upload-form-item .el-form-item__content {
  width: auto;
}
</style>
